package com.tc.quartz.support.service.impl;

import com.tc.quartz.frame.base.BaseService;
import com.tc.quartz.frame.base.IBaseDao;
import com.tc.quartz.support.bean.SystemDictBean;
import com.tc.quartz.support.dao.SystemDictDao;
import com.tc.quartz.support.service.ISystemDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * desc：任务管理
 * @author yongjin.ye
 */
@Service
public class SystemDictServiceImpl extends BaseService implements ISystemDictService {

	@Autowired
	private SystemDictDao systemDictDao;
	
	@Override
	public IBaseDao getBaseDao() {
		return this.systemDictDao;
	}
	
	private static volatile ConcurrentMap<String, SystemDictBean> dictCache = new ConcurrentHashMap<String, SystemDictBean>();

	@PostConstruct
	public void initDict2Cache() {
		List<SystemDictBean> list = this.getDict(null, null);
		for (int i = 0; null != list && i < list.size(); i++) {
			this.putDictCache(list.get(i));
		}
	}
	
	@Override
	public List<SystemDictBean> getDict(String dictType, String dictKey) {
		SystemDictBean search = new SystemDictBean();
		search.setDictType(dictType);
		search.setDictKey(dictKey);
		List<SystemDictBean> list = this.getBaseDao().select(search);
		return list;
	}

	@Override
	public SystemDictBean loadDict(String dictType, String dictKey) {
		if (null == dictType || null == dictKey) {
			throw new IllegalArgumentException("dictType、dictKey参数不能为null");
		}
		SystemDictBean dictBean = dictCache.get(String.format("%s|%s", dictType, dictKey));
		if (null == dictBean) {
			dictBean = this.getDict(dictType, dictKey).get(0);
			this.putDictCache(dictBean);
		}
		return dictBean;
	}

	@Override
	public ConcurrentMap<String, SystemDictBean> getDictCache() {
		return dictCache;
	}

	@Override
	public ConcurrentMap<String, SystemDictBean> putDictCache(SystemDictBean dict) {
		if (null != dict) {
			dictCache.put(String.format("%s|%s", dict.getDictType(), dict.getDictKey()), dict);
		}
		return dictCache;
	}
	
	
}
